//
//  CZComposeTextView.swift
//  Blog
//
//  Created by whitcast on 16/7/19.
//  Copyright © 2016年 itcast. All rights reserved.
//
// 实时看到xib设置的属性


import UIKit
@IBDesignable
class CZComposeTextView: UITextView {
    
    // MARK: -- 懒加载
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "赶紧写"
        label.textColor = UIColor.lightGrayColor()
        label.numberOfLines = 0
        return label
    }()
    // 占位文字
    // 设置xib属性
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    // 重写font
    override var font: UIFont? {
        didSet{
            // 如果外界传入nil直接返回
            if font == nil {
                return
            }
            placeHolderLabel.font = font
        }
    }
    // 重写text
    override var text: String? {
        didSet {
            placeHolderLabel.hidden = hasText()
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    // 支持xib
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    private func setupUI() {
        // 监听uitextView文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        addSubview(placeHolderLabel)
        // 使用手写布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))

    }
    // MARK: -- 懒加载
    @objc private func textChange() {
        // 判断有内容的话就隐藏占位label
        placeHolderLabel.hidden = self.hasText()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
